package cz.myslivec.slovicka.util.action;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.international.StatusMessage;
import org.jboss.seam.international.StatusMessages;
import org.jboss.seam.log.Log;

@Name("parsePageAction")
@AutoCreate
public class ParsePageAction implements Serializable {
	private static final long serialVersionUID = 1L;

	@Logger
	private Log log;


	private InputStream uploadedData;
	
	public void execute() {
		try {
			if (uploadedData != null) {
				executeInner(uploadedData);
			} else {
				StatusMessages.instance().addFromResourceBundle(StatusMessage.Severity.ERROR, "menu-setup.initial-load.xhtml.error.file_not_provided");
			}
		} catch (IOException e) {
			StatusMessages.instance().addFromResourceBundle(StatusMessage.Severity.ERROR, "menu-setup.initial-load.xhtml.error.parsing");
			log.error("Can not parse data",e);
		}

	}
	
	private void executeInner(InputStream inputStream) throws IOException {
		if (inputStream == null) {
			throw new IllegalArgumentException("Input stream can not be null");
		}

		List<String> result = new ArrayList<String>(); 
		Scanner scanner = new Scanner(inputStream);
		scanner.useDelimiter(System.getProperty("line.separator"));
        while (scanner.hasNext()) {
        	String parsedLine = parseLine(scanner.next());
        	if(parsedLine != null) {
        		result.add(parsedLine);
        	}
        }
        scanner.close();
        
        save(result);
	}
	
    private String parseLine(String line) {
    	line = line.trim();
    	
    	if(line.contains("tooltiptext")) {
    		line = line.replaceAll("(<b>|</b>|<br>|</br>|<i>|</i>|\")", "");
    		line = line.replaceAll(";", ":");
    		
    		int startEN = line.indexOf(">");
    		int endEN = line.indexOf("</font>");
    		
    		int startCZ = line.indexOf("title=");
    		int endCZ = line.indexOf("><img");
    		
    		String enStr = line.substring(startEN + 1, endEN).trim(); 
    		String czStr = line.substring(startCZ + 6, endCZ).trim();
    		
    		return enStr + ";" + czStr;
    	}
    	
    	return null;
    }
    
    public void save(List<String> outputList) {
    	if(outputList == null || outputList.isEmpty()) {
    		return;
    	}
    	
        FacesContext fc = FacesContext.getCurrentInstance(); 
        HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse(); 
        response.setContentType("application/force-download");
        //response.setContentType("text/html; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        String downloadFile = "parsed_vocables";
        response.addHeader("Content-Disposition", "attachment; filename=\"" + downloadFile + "\"");
        try{
          PrintWriter out = response.getWriter();
          for(String outStr : outputList) {
        	  out.println(outStr);
          }
          
          out.close();
        }catch (Exception exc){
          exc.printStackTrace();
        } 
        fc.responseComplete();
    }

	public InputStream getUploadedData() {
		return uploadedData;
	}

	public void setUploadedData(InputStream uploadedData) {
		this.uploadedData = uploadedData;
	}
}
